package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lawyer.config.QiniuConfigBean;
import com.lawyer.entity.RegimentalMember;
import com.lawyer.entity.StationRelStation;
import com.lawyer.entity.User;
import com.lawyer.entity.view.OrderRecommendView;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.qrode.QRCodeUtil;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.OrderRecommendViewRepository;
import com.lawyer.repository.OrderSuccessQuantityViewRepository;
import com.lawyer.repository.OrderTotalQuantityViewRepository;
import com.lawyer.repository.RegimentalMemberRepository;
import com.lawyer.repository.SettlementAmountViewRepository;
import com.lawyer.repository.StationRelStationRepository;
import com.lawyer.repository.UserRepository;
import com.lawyer.service.FileUpLoadService;
import com.lawyer.service.RegimentalMemberService;

@RestController
@RequestMapping(value = "/regimentalMember")
@Api(tags = "团员管理")
@SuppressWarnings("all")
public class RegimentalMemberController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;

	@Autowired
	private RegimentalMemberRepository regimentalMemberRepository;

	@Autowired
	private EntityManager entityManager;

	@Autowired
	private RegimentalMemberService regimentalMemberService;

	@Autowired
	private SettlementAmountViewRepository settlementAmountViewRepository;

	@Autowired
	private OrderTotalQuantityViewRepository orderTotalQuantityViewRepository;

	@Autowired
	private OrderSuccessQuantityViewRepository orderSuccessQuantityViewRepository;
	@Autowired
	private StationRelStationRepository stationRelStationRepository;
	@Autowired
	private OrderRecommendViewRepository orderRecommendViewRepository;

	@Autowired
	private QiniuConfigBean qiniuConfigBean;

	@Autowired
	private FileUpLoadService fileUpLoadService;


	@ApiOperation(httpMethod = "PUT", value = "绑定推荐站长", notes = "leaderId：站长ID,userId:被推荐站长的userId")
	@RequestMapping(value = "/recommend", method = RequestMethod.PUT)
	public HttpEntity<?> recommend(String leaderId, String userId) {
		Message msg = new Message();
		try {

			RegimentalMember mySelf = regimentalMemberRepository.findOne(leaderId);
			RegimentalMember userMember = regimentalMemberRepository.findOne(userId);

			if (mySelf == null || userMember == null) {
				msg.setMessage("只能站长绑定站长");
				msg.setCode(MessageConstant.FAILED_CODE);
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}
			String ids = mySelf.getId() + userId;
			String relId = UUID.nameUUIDFromBytes(ids.getBytes()).toString();
			StationRelStation exists = stationRelStationRepository.findOne(relId);

			if (exists != null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("请勿重复推荐");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			StationRelStation rel = new StationRelStation();
			rel.setId(relId);

			rel.setMyId(mySelf.getId());
			rel.setMyName(mySelf.getLeaderName());
			rel.setMyHeaderIco(mySelf.getLeaderHeaderIco());

			rel.setUserId(userId);
			rel.setUserName(userMember.getLeaderName());
			rel.setHeaderIco(userMember.getLeaderHeaderIco());
			rel.setPhone(userMember.getMemberPhone());
			stationRelStationRepository.save(rel);

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
	@ApiOperation(httpMethod = "PUT", value = "骑手绑定站长(入团)", notes = "StarLevel：1=员团，2=站长，3=团长")
	@RequestMapping(value = "/joinMental", method = RequestMethod.PUT)
	public HttpEntity<?> generalJoin(String leaderId, String memberId) {
		Message msg = new Message();
		RegimentalMember memberIdMember = regimentalMemberRepository.findOne(memberId);
		//绑定代理
		regimentalMemberService.binding(memberId, leaderId);
		
		if (memberIdMember != null && memberIdMember.getStarLevel() == 2) {
			// 站长加入团
			return regimentalMemberService.regimentJoin(leaderId, memberId);
		} else {
			// 骑手加入团
			return regimentalMemberService.generalJoin(leaderId, memberId);
		}

		
	}
	

	@ApiOperation(httpMethod = "GET", value = "判断是不是站长或团长", notes = "starLevel:1=员团，2=站长，3=团长")
	@RequestMapping(value = "/isMaster", method = RequestMethod.GET)
	public HttpEntity<?> isMaster(String userId) {
		Message msg = new Message();
		RegimentalMember memberIdMember = regimentalMemberRepository.findOne(userId);
		if(memberIdMember==null){
			msg.setData(1);
		}else {
			msg.setData(memberIdMember.getStarLevel());
		}
		
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "我的推荐站长列表(展示成员)", notes = "我的推荐站长列表")
	@RequestMapping(value = "/myRecommends", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> myRecommends(String userId, @PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();

		if (StringUtils.isEmpty(userId)) {
			msg.setCode(MessageConstant.SUCCESS_CODE);
			return new ResponseEntity<>(msg, HttpStatus.OK);
		}

		Page<StationRelStation> page = stationRelStationRepository.findByMyId(userId, pageable);
		msg.setData(page);

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "推荐站长订单列表（展示订单）", notes = "推荐站长订单列表")
	@RequestMapping(value = "/myRecommendOrders", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> myRecommendOrders(String userId, String orderStatus,
			@PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

		CriteriaQuery<OrderRecommendView> criteriaQuery = criteriaBuilder.createQuery(OrderRecommendView.class);

		Root<OrderRecommendView> root = criteriaQuery.from(OrderRecommendView.class);

		criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdDate")));

		// 查询条件
		List<Predicate> predicates = new ArrayList<>();

		predicates.add(criteriaBuilder.equal(root.get("myId"), userId));

		if (StringUtils.isNotEmpty(orderStatus) && !"全部".equals(orderStatus)) {
			predicates.add(criteriaBuilder.equal(root.get("orderStatus"), orderStatus));
		}

		// 将所有条件用 and 联合起来
		if (!CollectionUtils.isEmpty(predicates)) {
			criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
		}

		List<OrderRecommendView> counts = entityManager.createQuery(criteriaQuery).getResultList();
		TypedQuery<OrderRecommendView> createQuery = entityManager.createQuery(criteriaQuery);
		createQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
		createQuery.setMaxResults(pageable.getPageSize());

		Page page = new PageImpl<OrderRecommendView>(createQuery.getResultList(), pageable, counts.size());

		msg.setData(page);

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}



	@ApiOperation(httpMethod = "GET", value = "我的团成员查询", notes = "我的团成员查询")
	@RequestMapping(value = "/myRegimentalMember", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> myRegimentalMember(String userId, @PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();

		if (StringUtils.isEmpty(userId)) {
			msg.setCode(MessageConstant.SUCCESS_CODE);
			return new ResponseEntity<>(msg, HttpStatus.OK);
		}

		RegimentalMember leaderMember = regimentalMemberRepository.findOne(userId);
		if (leaderMember == null) {
			msg.setCode(MessageConstant.SUCCESS_CODE);
			return new ResponseEntity<>(msg, HttpStatus.OK);
		}
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

		CriteriaQuery<RegimentalMember> criteriaQuery = criteriaBuilder.createQuery(RegimentalMember.class);

		Root<RegimentalMember> root = criteriaQuery.from(RegimentalMember.class);

		criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdDate")));

		// 查询条件
		List<Predicate> predicates = new ArrayList<>();

		predicates.add(criteriaBuilder.notEqual(root.get("id"), userId));

		predicates.add(criteriaBuilder.like(root.get("topId"), "%" + userId + "%"));

		// 将所有条件用 and 联合起来
		if (!CollectionUtils.isEmpty(predicates)) {
			criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
		}

		List<RegimentalMember> counts = entityManager.createQuery(criteriaQuery).getResultList();
		TypedQuery<RegimentalMember> createQuery = entityManager.createQuery(criteriaQuery);
		createQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
		createQuery.setMaxResults(pageable.getPageSize());

		Page page = new PageImpl<RegimentalMember>(createQuery.getResultList(), pageable, counts.size());

		msg.setData(page);

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}


	@ApiOperation(httpMethod = "GET", value = "我的团队数据", notes = "团队数：regimentalQuantity;订单数：orderTotalQuantity;成功订单数：orderSuccessQuantity;已结算佣金数：settlementAmount")
	@RequestMapping(value = "/myRegimentalData", method = RequestMethod.GET)
	public HttpEntity<?> myRegimentalData(String userId) {
		Message msg = new Message();

		Map<String, Object> resutl = new HashMap<String, Object>();
		resutl.put("regimentalQuantity", 0);// 团队数
		resutl.put("orderTotalQuantity", 0);// 订单数
		resutl.put("orderSuccessQuantity", 0);// 成功订单数
		resutl.put("settlementAmount", 0);// 已结算拥金额

		try {
			List<RegimentalMember> regimentalQuantity = regimentalMemberService.findMyTeam(userId);

			double settlementAmount = 0D;
			Double settlementAmountDle = settlementAmountViewRepository.settlementAmount(userId);
			if (settlementAmountDle != null) {
				settlementAmount = new BigDecimal(settlementAmountDle).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			}

			Object orderTotalQuantity = orderTotalQuantityViewRepository.orderTotalQuantity(userId);

			Object orderSuccessQuantity = orderSuccessQuantityViewRepository.orderSuccessQuantity(userId);

			if (orderTotalQuantity == null) {
				orderTotalQuantity = 0;
			}
			if (orderSuccessQuantity == null) {
				orderSuccessQuantity = 0;
			}

			resutl.put("regimentalQuantity", regimentalQuantity.size());

			resutl.put("orderTotalQuantity", orderTotalQuantity);
			resutl.put("orderSuccessQuantity", orderSuccessQuantity);
			resutl.put("settlementAmount", settlementAmount);

			msg.setData(resutl);
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);

	}

	@ApiOperation(httpMethod = "GET", value = "邀请入团二维码", notes = "邀请入团二维码")
	@RequestMapping(value = "/joinedleagueQrCode", method = RequestMethod.GET)
	public HttpEntity<?> joinedleagueQrCode (@RequestParam(required = true, name = "userId") String userId) {
		Message msg = new Message();
		String qrCode = null;
		try {
			User user = userRepository.findOne(userId);

			if (StringUtils.isEmpty(user.getLeagueQrCode())) {
				String url = qiniuConfigBean.getServiceUrl() + "/regimental/group?type=league&userId=" + userId;
				InputStream input = QRCodeUtil.getImageStream(user.getHeaderIco());
				InputStream qrCodeInput = QRCodeUtil.encode(url, input, true);

				Message result = fileUpLoadService.Upload(qrCodeInput);
				if (MessageConstant.SUCCESS_CODE.equals(result.getCode())) {
					qrCode = result.getData().toString();
					user.setLeagueQrCode(qrCode);
					userRepository.save(user);
				}
			} else {
				qrCode = user.getLeagueQrCode();
			}

			msg.setData(qrCode);

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	
	@ApiOperation(httpMethod = "GET", value = "推荐站长二维码", notes = "推荐站长二维码")
	@RequestMapping(value = "/recommendQrCode", method = RequestMethod.GET)
	public HttpEntity<?> recommendQrCode(@RequestParam(required = true, name = "userId") String userId) {
		Message msg = new Message();
		String qrCode = null;
		try {
			User user = userRepository.findOne(userId);

			if (StringUtils.isEmpty(user.getRecommendQrCode())) {
				String url = qiniuConfigBean.getServiceUrl() + "/regimental/group?type=recommend&userId=" + userId;
				InputStream input = QRCodeUtil.getImageStream(user.getHeaderIco());
				InputStream qrCodeInput = QRCodeUtil.encode(url, input, true);

				Message result = fileUpLoadService.Upload(qrCodeInput);
				if (MessageConstant.SUCCESS_CODE.equals(result.getCode())) {
					qrCode = result.getData().toString();
					user.setRecommendQrCode(qrCode);
					userRepository.save(user);
				}
			} else {
				qrCode = user.getRecommendQrCode();
			}

			msg.setData(qrCode);

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

}
